package com.hy.heath.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.heath.common.BusinessException;
import com.hy.heath.mapper.HealthRecordMapper;
import com.hy.heath.pojo.entity.HealthRecord;
import com.hy.heath.service.HealthRecordService;
import com.hy.heath.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class HealthRecordServiceImpl extends ServiceImpl<HealthRecordMapper, HealthRecord> implements HealthRecordService {

    @Autowired
    private UserService userService;

    @Override
    public List<HealthRecord> listByUserId(Integer userId) {
        // 校验用户存在性
        if (userService.getById(userId) == null) {
            throw new BusinessException("用户不存在");
        }
        return this.list(new LambdaQueryWrapper<HealthRecord>()
                .eq(HealthRecord::getUserId, userId)
                .orderByDesc(HealthRecord::getRecordDate));
    }

    @Override
    public Page<HealthRecord> pageRecords(Page<HealthRecord> page, Integer userId) {
        LambdaQueryWrapper<HealthRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(HealthRecord::getUserId, userId);
        }
        queryWrapper.orderByDesc(HealthRecord::getRecordDate);
        return this.page(page, queryWrapper);
    }

    @Override
    public boolean save(HealthRecord entity) {
        validateHealthRecord(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(HealthRecord entity) {
        validateHealthRecord(entity);
        return super.updateById(entity);
    }

    // 校验必填字段
    private void validateHealthRecord(HealthRecord record) {
        if (record.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (!StringUtils.hasText(record.getRecordType())) {
            throw new BusinessException("记录类型不能为空");
        }
        if (record.getRecordDate() == null) {
            throw new BusinessException("记录日期不能为空");
        }
    }
}